﻿using System.Diagnostics;
using System.Text.RegularExpressions;
using System;
using System.IO;
using Microsoft.WindowsAPICodePack.Dialogs;

namespace ThunderboltHelper;

public static class FileHelper
{
	/// <summary>
	/// 使用文件管理器打开目录且选中文件,用于打开文件夹
	/// </summary>
	/// <param name="filePathAndName">文件的路径和名称（比如：C:\Users\Administrator\test.txt）</param>
	private static void OpenFolderAndSelectedSpecifiedFile(this string filePathAndName)
	{
		if (string.IsNullOrEmpty(filePathAndName)) return;

		Process process = new Process();
		ProcessStartInfo psi = new ProcessStartInfo("Explorer.exe");
		psi.Arguments = "/e,/select," + filePathAndName;
		process.StartInfo = psi;

		//process.StartInfo.UseShellExecute = true;
		try
		{
			process.Start();
		}
		catch (Exception ex)
		{
			throw ex;
		}
		finally
		{
			process?.Close();

		}
	}
	/// <summary>
	/// 使用文件管理器打开文件
	/// </summary>
	/// <param name="filePathAndName">文件的路径和名称（比如：C:\Users\Administrator\test.txt）</param>
	/// <param name="isWaitFileClose">是否等待文件关闭（true：表示等待）</param>
	private static void OpenSpecifiedFile(this string filePathAndName, bool isWaitFileClose = true)
	{
		Process process = new Process();
		ProcessStartInfo psi = new ProcessStartInfo(filePathAndName);
		process.StartInfo = psi;

		process.StartInfo.UseShellExecute = true;

		try
		{
			process.Start();

			//等待打开的程序关闭
			if (isWaitFileClose)
			{
				process.WaitForExit();
			}

		}
		catch (Exception ex)
		{
			throw ex;
		}
		finally
		{
			process?.Close();

		}
	}
	/// <summary>
	/// 判断打开的文件是否被其他程序占用，返回指示文件是否已被其它程序使用的布尔值
	/// </summary>
	/// <param name="fileFullName">给定的文件完整路径</param>
	/// <returns>如果文件已被其它程序使用，则为 true；否则为 false</returns>
	private static bool SpecifiedFileIsUsed(this string fileFullName)
	{
		bool result = false;
		if (!System.IO.File.Exists(fileFullName))//判断文件是否存在，如果不存在，直接返回 false
		{
			result = false;
		}
		else//如果文件存在，则继续判断文件是否已被其它程序使用
		{
			//逻辑：尝试执行打开文件的操作，如果文件已经被其它程序使用，则打开失败，抛出异常，根据此类异常可以判断文件是否已被其它程序使用。
			System.IO.FileStream fileStream = null;
			try
			{
				fileStream = System.IO.File.Open(fileFullName, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None);
				result = false;
			}
			catch (System.IO.IOException ioEx)
			{
				result = true;
			}
			catch (System.Exception ex)
			{
				result = true;
			}
			finally
			{
				if (fileStream != null)
				{
					fileStream.Close();
				}
			}
		}
		return result;
	}
	/// <summary>
	/// 使用文件管理器打开指定目录
	/// </summary>
	/// <param name="folderPath">目录路径（比如：C:\Users\Administrator\）</param>
	public static bool OpenSpecifiedFolder(this string folderPath)
	{
		if (string.IsNullOrEmpty(folderPath)) return false;
		if (!GetIsTheFolderPathLegal(folderPath)) return false;
		Process process = new Process();
		ProcessStartInfo psi = new ProcessStartInfo("Explorer.exe");
		psi.Arguments = folderPath;
		process.StartInfo = psi;
		try
		{
			if (process.Start())
			{
				return true;
			}
			return false;
		}
		catch (Exception ex)
		{
			throw ex;
		}
		finally
		{
			process?.Close();

		}

	}
	/// <summary>
	/// 判断给定目录路径是否合法
	/// </summary>
	/// <param name="folderPath">目录路径（比如：C:\Users\Administrator\）</param>
	public static bool GetIsTheFolderPathLegal(this string folderPath)
	{
		try
		{
			if(string.IsNullOrEmpty(folderPath)) return false;
			var regex = new Regex(@"^[a-zA-Z]:((\\+[^\/:*?""<>|]+)+)\s*$");
			return regex.Match(folderPath).Success;
		}
		catch (Exception ex)
		{
			throw ex;
		}
	}

	/// <summary>
	/// 判断给定文件完整路径是否合法
	/// </summary>
	/// <param name="filePath">文件路径（比如：C:\Users\Administrator\a.txt）</param>
	public static bool GetIsTheSpecifiedFilePathLegal(this string filePath)
	{
		try
		{
			if(string.IsNullOrEmpty(filePath)) return false;
			var fileName = Path.GetFileName(filePath);
			if (fileName.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) >= 0)
			{
				//文件名含有非法字符
				return false;
			}
			var directoryName = Path.GetDirectoryName(filePath);
			if (directoryName.GetIsTheFolderPathLegal())
			{
				//所在目录含有非法字符
				return false;
			}
			return true;
		}
		catch (Exception ex)
		{
			throw ex;
		}
	}


	/// <summary>
	/// 打开文件夹浏览框并返回选定的目录
	/// </summary>
	/// <returns>选择的文件夹路径</returns>
	public static string GetFolderBrowserDialogSelectedPath(this string str)
	{
		var dialog = new CommonOpenFileDialog();
		dialog.Title = "请选择指定区域存储下载文件";
		dialog.IsFolderPicker = true;
		if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
			str = dialog.FileName;
		else str = null;
			return str;
	}
}